/**
 * 
 * log.log        0     调试，要丢弃 **
 * log.trace      1     
 * log.debug      2     调试，要保留
 * log.info       3     重要信息，要保留 **
 * log.warn       4     不重要的非法信息（一般不用）
 * log.error      5     错误，要保留 **
 */

var FileStreamRotator = require('file-stream-rotator');
var fs = require('fs');
var config = require('../config/config');

//调试日志路径
var logDebugDirectory = process.cwd() + '/log/debug';
//运行时日志路径
var logInfoDirectory = process.cwd() + '/log/info';
//错误日志路径
var logErrorDirectory = process.cwd() + '/log/error';

fs.existsSync(process.cwd() + '/log') || fs.mkdirSync(process.cwd() + '/log');
fs.existsSync(logDebugDirectory) || fs.mkdirSync(logDebugDirectory);
fs.existsSync(logInfoDirectory) || fs.mkdirSync(logInfoDirectory);
fs.existsSync(logErrorDirectory) || fs.mkdirSync(logErrorDirectory);

var logStream = function(directory) {
  return FileStreamRotator.getStream({
    filename: directory + '/log_%DATE%.log',
    verbose: false,
    frequency: '60m'
  });
};

var level = config.loglevel || 0;

var logger = {
  debugLogger: require('tracer').console({
    transport: function(data) {
      logStream(logDebugDirectory).write(data.output + '\r\n');
    },
    level: level
  }),
  infoLogger: require('tracer').console({
    transport: function(data) {
      logStream(logInfoDirectory).write(data.output + '\r\n');
    },
    level: level
  }),
  errorLogger: require('tracer').console({
    transport: function(data) {
      logStream(logErrorDirectory).write(data.output + '\r\n');
    },
    level: level
  })
};

logger.logError = function(jsonobj, title) {
  logger.errorLogger.error(title ? '%s:\r\n %j' : '%s%j', title || '', jsonobj);
  return jsonobj;
};

logger.logInfo = function(jsonobj, title) {
  logger.infoLogger.info(title ? '%s:\r\n %j' : '%s%j', title || '', jsonobj);
  return jsonobj;
};

logger.logDebug = function(jsonobj, title) {
  logger.debugLogger.debug(title ? '%s:\r\n %j' : '%s%j', title || '', jsonobj);
  return jsonobj;
};

module.exports = logger;
